#include "PlantDictionary.h"
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <iostream>

//#define TIXML_USE_STL
#include <tinyxml.h>

PlantDictionary::PlantDictionary() : numTrees(0), numShrubs(0)
{
}

PlantModel PlantDictionary::getTreeModel(std::string name)
{
    if (trees.count(name)) return trees[name];
    else return trees["DEFAULT"];
}

PlantModel PlantDictionary::getShrubModel(std::string name)
{
    if (shrubs.count(name)) return shrubs[name];
    else return shrubs["DEFAULT"];
}

int PlantDictionary::getNumTrees()
{
    return numTrees;
}

int PlantDictionary::getNumShubs()
{
    return numShrubs;
}

void PlantDictionary::loadPlants(std::string path)
{
    path += "/";
    std::ifstream indexFile(path+"index.txt", std::ios::in);
    if (!indexFile.is_open()) return;
    std::string line;
    while (indexFile.good())
    {
        std::getline(indexFile,line);
        TiXmlDocument doc((path+line).c_str());
        if (!doc.LoadFile()) continue;
        
        TiXmlElement *root  = doc.FirstChildElement();
        TiXmlElement *model = root->FirstChildElement("model");
        while (model)
        {
            double minScale, maxScale;
            std::string modelName = model->Attribute("name");
            model->Attribute("minScale",&minScale);
            model->Attribute("maxScale",&maxScale);

            TiXmlElement *plant = model->FirstChildElement("plant");
            while (plant)
            {
                std::string plantName = plant->Attribute("name");
                std::string plantType = plant->Attribute("type");

                PlantModel pm;
                pm.name = modelName;
                pm.minScale = (float)minScale;
                pm.maxScale = (float)maxScale;

                if (boost::iequals(plantType,"tree"))
                {
                    trees[plantName] = pm;
                    numTrees++;
                }
                else if (boost::iequals(plantType,"shrub"))
                {
                    shrubs[plantName] = pm;
                    numShrubs++;
                }
                plant = plant->NextSiblingElement("plant");
            }
            model = model->NextSiblingElement("model");
        }
    }
}